package com.zdzx.controller.admin.content;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdzx.base.common.util.RedisUtil;
import com.zdzx.base.common.util.UserInfoUtil;
import com.zdzx.common.result.PageInfo;
import com.zdzx.common.result.PageUtil;
import com.zdzx.common.result.Result;
import com.zdzx.common.result.ResultCode;
import com.zdzx.common.result.ResultUtil;
import com.zdzx.mapper.CourseMapper;
import com.zdzx.mapper.CourseTypeMapper;
import com.zdzx.model.constant.SystemConfig;
import com.zdzx.model.service.base.result.UserInfo;
import com.zdzx.model.service.content.param.UserWatchCourse;
import com.zdzx.model.service.content.vo.Course;
import com.zdzx.model.service.content.vo.CourseType;
import com.zdzx.service.OSSService;
import com.zdzx.utils.PoiUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(tags = "课程")
@RestController
@RequestMapping("/admin")
public class DaCourseController {


	@Autowired
	private CourseMapper courseMapper;
	@Autowired
	private CourseTypeMapper courseTypeMapper;
	@Autowired
	private OSSService ossService;
	@Autowired
	private RedisUtil redisUtil;


	
	
	@ApiOperation(value = "获取列表", notes = "")
	@GetMapping("/course/da")
	public Result<PageInfo<Course>> listda(
			@ApiParam("") @RequestParam(value = "pageNum", required = false) Integer pageNum,
			@ApiParam("") @RequestParam(value = "pageSize", required = false) Integer pageSize,
			@ApiParam("") @RequestParam(value = "title", required = false) String title,
			@ApiParam("0视频 1文章 2直播") @RequestParam(value = "type", required = false) String type,
			@ApiParam("课程分类") @RequestParam(value = "courseType", required = false) String courseType,
			HttpServletRequest request
			){
		UserInfo loginInfo = UserInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
		if (loginInfo == null) {
			return ResultUtil.data(ResultCode.NOT_LOGIN.getCode(), ResultCode.NOT_LOGIN.getMes(), null);
		}
		Page<Course> page = new Page<>(pageNum, pageSize);
		QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
		if (!StringUtils.isEmpty(title)) {
			queryWrapper.like("title", title);
		}
			queryWrapper.eq("tenant_id", loginInfo.getTenantId());
		
		if (!StringUtils.isEmpty(type)) {
			queryWrapper.eq("type", type);
		}
		
		
		queryWrapper.eq("parent_id", "0");
		queryWrapper.orderByDesc("update_time");
		
		queryWrapper.select("id", "title", "lecturer","type","create_time", "views","path","dcount","scount","sum_count");
		//queryWrapper.eq("parent_id", "0");
		IPage<CourseType> selectPage=null;
		if (!StringUtils.isEmpty(courseType)) {
			Page<CourseType> page1 = new Page<>(pageNum == null ? 1 : pageNum, pageSize == null ? 10 : pageSize);
			QueryWrapper<CourseType> queryWrapper1=new QueryWrapper<CourseType>();
			List<String> ctype=new ArrayList<String>();
			if(courseType.contains(",")) {
				String[] split = courseType.split(",");
				for (String string : split) {
					ctype.add(string);
				}
			}else {
				ctype.add(courseType );
			}
			queryWrapper1.groupBy("course_id");
			
			selectPage = courseTypeMapper.selectPageByType(page1,ctype,ctype.size(),loginInfo.getTenantId());
			List<String> ids=new ArrayList<String>();
			for(CourseType t : selectPage.getRecords()) {
				ids.add(t.getCourseId());
			}
			if(ids.size()==0)
				ids.add("0");
			queryWrapper.in("id", ids);
		}
		
		
		IPage<Course> info = courseMapper.selectPage(page, queryWrapper);
		List<Course> records = info.getRecords();
		for (int i = 0; i < records.size(); i++) {
			records.get(i).getId();
			QueryWrapper<CourseType> queryWrapper1=new QueryWrapper<CourseType>();
			queryWrapper1.eq("course_id", records.get(i).getId());
			List<CourseType> selectList = courseTypeMapper.selectList(queryWrapper1);
			String courseTypeNew="";
			for (CourseType courseType2 : selectList) {
				if(StringUtils.isEmpty(courseTypeNew)) {
					courseTypeNew=courseType2.getPtype()+":"+courseType2.getTypeCode();
				}else {
					courseTypeNew=courseTypeNew+","+courseType2.getPtype()+":"+courseType2.getTypeCode();
				}
			}
			records.get(i).setCourseType(courseTypeNew);
		}
		for (int i=0;i<records.size();i++) {
			if(!StringUtils.isEmpty(records.get(i).getPath())) {
				String data = records.get(i).getPath();
				String newData = data.replace(SystemConfig.ossIp, "");
				String bucketName=newData.substring(0, newData.indexOf("/"));
				String objectName=newData.replace(bucketName, "");
				Result<String> url = ossService.getUrl(bucketName, objectName);
				records.get(i).setPath(url.getData());
			}
		}
		PageInfo<Course> data = PageUtil.data(StringUtils.isEmpty(courseType)?info.getPages():selectPage.getPages(),
				StringUtils.isEmpty(courseType)?info.getCurrent():selectPage.getCurrent(), StringUtils.isEmpty(courseType)?info.getTotal():selectPage.getTotal(), records);
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, data);
	}
	
	

	
	
	@ApiOperation(value = "添加", notes = "")
	@PostMapping("/course/single")
	@Transactional(rollbackFor = Exception.class)
	public Result<String> saveSingle(@RequestBody Course entity,HttpServletRequest request){
		UserInfo loginInfo = UserInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
		if (loginInfo == null) {
			return ResultUtil.data(ResultCode.NOT_LOGIN.getCode(), ResultCode.NOT_LOGIN.getMes(), null);
		}
		int result = 0;
		entity.setParentId("0");
	//	entity.setDataPath(entity.getDataPath()!=null?entity.getDataPath().replace(SystemConfig.ossIp, ""):"",false);
	//	entity.setDataImage(entity.getDataImage()!=null?entity.getDataImage().replace(SystemConfig.ossIp, ""):"",false);
	//	entity.setTitleImage(entity.getTitleImage()!=null?entity.getTitleImage().replace(SystemConfig.ossIp, ""):"",false);
	//	entity.setPath(entity.getPath()!=null?entity.getPath().replace(SystemConfig.ossIp, ""):"",false);
		entity.setCreateTime(LocalDateTime.now());
		entity.setUpdateTime(LocalDateTime.now());
		//if(StringUtils.isEmpty(entity.getCourseType())) {
		//	return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "课程类型不能为空！！！",null);
		//}
			
		entity.setTenantId(loginInfo.getTenantId());
		entity.setIsPackage(0);
		if(StringUtils.isEmpty(entity.getFree())) {
			entity.setFree("1");
		}
		String courseType=entity.getCourseType();
		entity.setCourseType("");
		result = courseMapper.insert(entity);
		if (result > 0) {
			String[] split = courseType.split(",");
			for (String string : split) {
				if(string.split(":").length>1) {
					CourseType entity1=new CourseType();
					entity1.setCourseId(entity.getId());
					entity1.setTypeCode(string.split(":")[1]);
					entity1.setPtype(string.split(":")[0]);
					courseTypeMapper.insert(entity1);
				}
			}
			return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, entity.getId());
		} else {
			return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), ResultCode.RESULT_ERROR.getMes(), null);
		}
	}
	@ApiOperation(value = "修改", notes = "")
	@PutMapping("/course/single")
	@Transactional(rollbackFor = Exception.class)
	public Result<String> editSingle(@RequestBody Course entity,HttpServletRequest request){
		UserInfo loginInfo = UserInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
		if (loginInfo == null) {
			return ResultUtil.data(ResultCode.NOT_LOGIN.getCode(), ResultCode.NOT_LOGIN.getMes(), null);
		}
		int result = 0;
	//	entity.setDataPath(entity.getDataPath()!=null?entity.getDataPath().replace(SystemConfig.ossIp, ""):"",false);
	//	entity.setDataImage(entity.getDataImage()!=null?entity.getDataImage().replace(SystemConfig.ossIp, ""):"",false);
	//	entity.setTitleImage(entity.getTitleImage()!=null?entity.getTitleImage().replace(SystemConfig.ossIp, ""):"",false);
	//	entity.setPath(entity.getPath()!=null?entity.getPath().replace(SystemConfig.ossIp, ""):"",false);
		entity.setViews(null);
		entity.setUpdateTime(LocalDateTime.now());
		/*if(StringUtils.isEmpty(entity.getCourseType())) {
			return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "课程类型不能为空！！！",null);
		}*/
		if(StringUtils.isEmpty(entity.getPath())) {
			return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "课程内容不能为空！！！",null);
		}
		String courseType=entity.getCourseType();
		entity.setTenantId(loginInfo.getTenantId());
		entity.setCourseType("");
		result = courseMapper.updateById(entity);
		if (result > 0) {
			String[] split = courseType.split(",");
			QueryWrapper<CourseType> wrapper1=new QueryWrapper<CourseType>();
			wrapper1.eq("course_id", entity.getId());
			courseTypeMapper.delete(wrapper1);
			for (String string : split) {
				if(string.split(":").length>1) {
					CourseType entity1=new CourseType();
					entity1.setCourseId(entity.getId());
					entity1.setTypeCode(string.split(":")[1]);
					entity1.setPtype(string.split(":")[0]);
					courseTypeMapper.insert(entity1);
				}
				
			}
			return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, null);
		} else {
			return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), ResultCode.RESULT_ERROR.getMes(), null);
		}
	}

		
	//---------------------------------------
	@ApiOperation(value = "企业用户学习记录", notes = "")
	@GetMapping("/course/user/watchCourse")
	public Result<PageInfo<UserWatchCourse>> watchCourse(
			@ApiParam("") @RequestParam(value = "pageNum", required = false) Integer pageNum,
			@ApiParam("") @RequestParam(value = "pageSize", required = false) Integer pageSize,
			@ApiParam("") @RequestParam(value = "startTime", required = false) String startTime,
			@ApiParam("") @RequestParam(value = "endTime", required = false) String endTime,
			@ApiParam("") @RequestParam(value = "sort", required = false) String sort,
			HttpServletRequest request){
		UserInfo loginInfo = UserInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
		if (loginInfo == null) {
			return ResultUtil.data(ResultCode.NOT_LOGIN.getCode(), ResultCode.NOT_LOGIN.getMes(), null);
		}
		if(!StringUtils.isEmpty(startTime)&&StringUtils.isEmpty(endTime)||StringUtils.isEmpty(startTime)&&!StringUtils.isEmpty(endTime)) {
			return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "时间不正确",null);
		}
		if(!StringUtils.isEmpty(startTime)&&!StringUtils.isEmpty(endTime)) {
			startTime+=" 00:00:00";
			endTime+=" 23:59:59";
		}
		Page<UserWatchCourse> page=new Page<UserWatchCourse>(pageNum,pageSize);
		IPage<UserWatchCourse> info = courseMapper.userWatchCourse(page,"-1",loginInfo.getTenantId(),startTime,endTime,sort);
		List<UserWatchCourse> records = info.getRecords();
		if(info.getRecords().size()>0) {
			for (int i=0;i<info.getRecords().size();i++) {
				UserWatchCourse userWatchCourse = records.get(i);
				List<UserWatchCourse> userWatchCourseChildren = courseMapper.userWatchCourseChildren(userWatchCourse.getId(),userWatchCourse.getUserId());
				userWatchCourse.setChildren(userWatchCourseChildren);
				records.set(i, userWatchCourse);
			}
		}
		info.setRecords(records);
		PageInfo<UserWatchCourse> data = PageUtil.data(info.getPages(), info.getCurrent(), info.getTotal(), info.getRecords());
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(),null,data);
	}
	
	@ApiOperation(value = "企业用户总学习时长", notes = "")
	@GetMapping("/course/user/watchCourse/count")
	public Result<Integer> watchCourse(@ApiParam("") @RequestParam(value = "tenantId", required = false) String tenantId,
			HttpServletRequest request){
		
		Integer count = courseMapper.userWatchCourseCount(tenantId);
		
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(),null,count==null?0:count);
	}
	
	
	@ApiOperation(value = "导出企业用户学习记录", notes = "")
	@GetMapping("/course/user/watchCourse/export")
	public void watchCourseExport(
			@ApiParam("") @RequestParam(value = "tenantId", required = false) String tenantId,
			@ApiParam("") @RequestParam(value = "startTime", required = false) String startTime,
			@ApiParam("") @RequestParam(value = "endTime", required = false) String endTime,
			HttpServletRequest request,HttpServletResponse response) throws IOException{
		if(!StringUtils.isEmpty(startTime)&&!StringUtils.isEmpty(endTime)) {
			startTime+=" 00:00:00";
			endTime+=" 23:59:59";
		}
		Page<UserWatchCourse> page=new Page<UserWatchCourse>(1,100000);
		IPage<UserWatchCourse> info = courseMapper.userWatchCourse(page,"-1",tenantId,startTime,endTime,"1");
		List<UserWatchCourse> records = info.getRecords();
		if(info.getRecords().size()>0) {
			for (int i=0;i<info.getRecords().size();i++) {
				UserWatchCourse userWatchCourse = records.get(i);
				List<UserWatchCourse> userWatchCourseChildren = courseMapper.userWatchCourseChildren(userWatchCourse.getId(),userWatchCourse.getUserId());
				userWatchCourse.setChildren(userWatchCourseChildren);
				records.set(i, userWatchCourse);
			}
		}
		List<String[]> data=new ArrayList<String[]>();
		String[] header= {"账号","姓名","课程类型","课程标题","学习时长","最后学习时间"};
		for (UserWatchCourse tempUserWatchCourse : records) {
			String[] temp= {tempUserWatchCourse.getAccount(),tempUserWatchCourse.getRealName(),
					tempUserWatchCourse.getType().equals("0")?"视频":"文章",tempUserWatchCourse.getTitle(),
							tempUserWatchCourse.getCountTime()+"秒",tempUserWatchCourse.getUpdateTime()};
			data.add(temp);
		}
		PoiUtil.export(data, header, null, response, request);
	}
	
	
}
